/**
 * @Author 韦建韩
 * @Date 2022/8/5
 */
package com.example.devops.web.interceptor;

import com.example.devops.Conntext.TokenContext;
import com.example.devops.util.RedisUtil;
import com.example.devops.util.SpringUtil;
import com.wjh.util.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Slf4j
public class PermissionInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        String token = null;
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            if("token".equals(name)){
                token = cookie.getValue();
            }

        }
        if(Objects.isNull(token)){
            return false;
        }
        try{
            RedisUtil redis = SpringUtil.getBean(RedisUtil.class);
            Claims claims = JWTUtil.parseJWT(token, TokenContext.tokenKey);
            String subject = claims.getSubject();
            String value = redis.getkey(subject);
            if(Objects.nonNull(value)){
                return true;
            }
        }
        catch (Exception e){
            log.info("access failure, token:{}", token, e);
            return false;
        }

        return false;
    }
}
